'use strict';
const config = require('../config');
const nodePath = require('path');
const { multipleWhitespacesToSingle, sanitizeFilename } = require('../components/utils');

const cleanName = (name) => {
  return multipleWhitespacesToSingle(sanitizeFilename(name));
};

const saveLayout = (trackInfos, dirPath) => {
  let layout = config.get('saveLayout');
  let path = layout.path.match(/(?<=\{)[^\}]*/g);
  let file = layout.file.match(/(?<=\{)[^\}]*/g);

  if (path) {
    for (const v of path) {
      if (trackInfos[v]) {
        layout.path = layout.path.replace('{' + v + '}', cleanName(trackInfos[v]));
      } else {
        layout.path = layout.path.replace('{' + v + '}', '');
      }
    }
    layout.path = nodePath.join(dirPath, layout.path);
  } else {
    layout.path = nodePath.join(dirPath);
  }

  if (file) {
    for (const v of file) {
      if (trackInfos[v]) {
        layout.file = layout.file.replace('{' + v + '}', trackInfos[v]);
      } else {
        layout.file = layout.file.replace('{' + v + '}', '');
      }
    }
  } else {
    layout.file = cleanName(trackInfos.SNG_TITLE_VERSION);
  }

  if (layout.trackNumber && trackInfos.TRACK_POSITION) {
    layout.file = trackInfos.TRACK_POSITION + ' - ' + layout.file;
  }

  return multipleWhitespacesToSingle(layout.path).trim() + nodePath.sep + cleanName(layout.file).trim();
};

module.exports = saveLayout;
